'use strict';
const express = require('express');
const router = express.Router();
const qs = require('querystring');
const request = require('request');

const config = require('../config');

router.get('/', function (req, res, next) {
    if (req.query.code == null) {
        let gname = req.query.game_name;
        if (gname == null) {
            gname = 'mjhz';
        }
        let myparam = {
            game_name: gname,
        };
        if (req.query.room_id) {
            myparam.room_id = req.query.room_id;
        }
        let state = qs.stringify(myparam);
        //console.log(state);
        let queryParams = {
            appid: config.appId,
            redirect_uri: 'http://www.silinan.com/wx_play/',
            response_type: 'code',
            scope: 'snsapi_userinfo',
            secret: config.appSecret,
            state: state
        };

        let oauthUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
            qs.stringify(queryParams) + '#wechat_redirect';
        // 跳转到授权页面
        res.redirect(oauthUrl);
        return;
    }
    let code = req.query.code;
    //console.log(req.query.state);
    let myparam = qs.parse(req.query.state);

    // 我们的游戏服务器只要有code就可以了，后面的流程游戏服务器自己走
    let play_url = 'http://www.silinan.com/';
    let playParams = {
        code: code,
        room_id: myparam.room_id
    };
    if (myparam.game_name == 'mjhz') {
        play_url += 'mjhz-mobile/?' + qs.stringify(playParams);
    } else if (myparam.game_name == 'mjjy') {
        play_url += 'mjjy-mobile/?' + qs.stringify(playParams);
    }
    console.log(play_url);
    res.redirect(play_url);
    return;

    // getOAuthAccessToken(code, function (err, result) {
    //     if (err) {
    //         console.log('get oauth access_token failed!');
    //         return;
    //     }
    //     console.log(result);
    //     let access_token = result.access_token;
    //     let openid = result.openid;

    //     if (access_token == null || openid == null) {
    //         return;
    //     }

    //     // 获取用户信息...
    // });
});

module.exports = router;
